const app = getApp()

Page({
  data: {
    examId: null,
    exam: {},
    examRecords: [],
    hasParticipated: false,
    showStartDialog: false,
    loading: true
  },

  onLoad(options) {
    const examId = options.id
    const startExam = options.start === 'true'
    
    this.setData({ examId })
    this.loadExamDetail(examId)
    this.loadExamRecords(examId)
    
    if (startExam) {
      this.showStartDialog()
    }
  },

  // 加载考试详情
  loadExamDetail(examId) {
    wx.showLoading({ title: '加载中...' })

    wx.request({
      url: `${app.globalData.baseUrl}/exams/${examId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({ 
            exam: res.data.data,
            loading: false
          })
          
          // 设置页面标题
          wx.setNavigationBarTitle({
            title: res.data.data.title
          })
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('加载考试详情失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 加载考试记录
  loadExamRecords(examId) {
    if (!app.globalData.userInfo) return

    wx.request({
      url: `${app.globalData.baseUrl}/exams/${examId}/records`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          const records = res.data.data
          this.setData({
            examRecords: records,
            hasParticipated: records.length > 0
          })
        }
      },
      fail: (err) => {
        console.error('加载考试记录失败:', err)
      }
    })
  },

  // 显示开始考试弹窗
  showStartDialog() {
    // 检查用户是否已登录
    if (!app.globalData.userInfo) {
      wx.showModal({
        title: '提示',
        content: '请先登录后再参加考试',
        showCancel: false
      })
      return
    }

    // 检查是否已经参加过
    if (this.data.hasParticipated) {
      wx.showModal({
        title: '提示',
        content: '您已经参加过该考试，是否查看考试结果？',
        success: (res) => {
          if (res.confirm) {
            this.viewHistory()
          }
        }
      })
      return
    }

    this.setData({ showStartDialog: true })
  },

  // 关闭开始考试弹窗
  closeStartDialog() {
    this.setData({ showStartDialog: false })
  },

  // 确认开始考试
  confirmStartExam() {
    this.setData({ showStartDialog: false })
    
    // 开始考试
    wx.request({
      url: `${app.globalData.baseUrl}/exams/${this.data.examId}/start`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          // 跳转到考试页面
          wx.redirectTo({
            url: `/pages/exam-taking/exam-taking?exam_id=${this.data.examId}&record_id=${res.data.data.record_id}`
          })
        } else {
          wx.showToast({
            title: res.data.message || '开始考试失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('开始考试失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  },

  // 开始考试
  startExam() {
    this.showStartDialog()
  },

  // 查看历史记录
  viewHistory() {
    if (this.data.examRecords.length > 0) {
      const latestRecord = this.data.examRecords[0]
      wx.navigateTo({
        url: `/pages/exam-result/exam-result?record_id=${latestRecord.id}`
      })
    }
  },

  // 查看考试记录
  viewRecord(e) {
    const recordId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/exam-result/exam-result?record_id=${recordId}`
    })
  },

  // 返回列表
  goBack() {
    wx.navigateBack()
  }
}) 